<template>
  <div class="order-detail-page">
    <nut-pull-refresh v-model="refreshing" @refresh="loadOrderDetail">
      <div v-if="loading && !orderDetail" class="loading-state">
        <div class="loading-text">加载中...</div>
      </div>

      <div v-else-if="orderDetail" class="detail-content">
        <!-- 顶部支付状态 -->
        <div class="order-status-header">
          <div class="status-icon-wrapper">
            <component
              :is="getStatusIcon(orderDetail.orderStatus)"
              :class="`status-icon status-${orderDetail.orderStatus || 'default'}`"
            />
          </div>
          <div class="status-text">{{ orderDetail.orderStatusName || '--' }}</div>
        </div>

        <!-- 订单基本信息 -->
        <nut-cell-group title="订单信息">
          <nut-cell title="订单编号" :desc="orderDetail.orderNo || '--'" />
          <nut-cell title="产品名称" :desc="orderDetail.productName || '--'" />
          <nut-cell title="所属经销商" :desc="orderDetail.distributorName || '--'" />
          <nut-cell title="订单时间" :desc="formatTime(orderDetail.orderTime)" />
          <nut-cell title="订单状态">
            <template #desc>
              <nut-tag :type="getStatusTagType(orderDetail.orderStatus)">{{ orderDetail.orderStatusName || '--' }}</nut-tag>
            </template>
          </nut-cell>
          <nut-cell title="审核状态">
            <template #desc>
              <nut-tag :type="getReviewStatusTagType(orderDetail.reviewStatus)">{{ orderDetail.reviewStatusName || '--' }}</nut-tag>
            </template>
          </nut-cell>
        </nut-cell-group>

        <!-- 金额信息 -->
        <nut-cell-group title="支付信息">
          <nut-cell title="订单总金额" :desc="formatAmount(orderDetail.totalAmount)" />
          <nut-cell title="已支付金额" :desc="formatAmount(orderDetail.paidAmount)" />
          <nut-cell title="未支付金额" :desc="formatAmount(orderDetail.unpaidAmount)" />
          <nut-cell title="优惠金额" :desc="formatAmount(orderDetail.discountAmount)" />
        </nut-cell-group>

        <!-- 客户信息 -->
        <nut-cell-group title="客户信息">
          <nut-cell title="客户姓名" :desc="orderDetail.customName || '--'" />
          <nut-cell title="客户手机号" :desc="orderDetail.customPhone || '--'" />
          <nut-cell title="证件类型" :desc="orderDetail.idTypeName || '--'" />
          <nut-cell title="客户证件号" :desc="orderDetail.customIdCard || '--'" />
          <nut-cell v-if="orderDetail.customEmail" title="客户邮箱" :desc="orderDetail.customEmail" />
        </nut-cell-group>

        <!-- 车辆信息 -->
        <nut-cell-group v-if="hasVehicleInfo" title="车辆信息">
          <nut-cell title="车架号" :desc="orderDetail.vinCode || '--'" />
          <nut-cell title="发动机号" :desc="orderDetail.engineNumber || '--'" />
          <nut-cell title="车牌号" :desc="orderDetail.licensePlateNumber || '--'" />
          <nut-cell title="车辆类型" :desc="orderDetail.vehicleType || '--'" />
          <nut-cell title="品牌型号" :desc="orderDetail.model || '--'" />
          <nut-cell title="使用性质" :desc="orderDetail.useNature || '--'" />
          <nut-cell v-if="orderDetail.passengerCapacity" title="核载人数" :desc="orderDetail.passengerCapacity" />
          <nut-cell title="新车发票价" :desc="formatAmount(orderDetail.carPrice)" />
          <nut-cell title="购车发票日期" :desc="formatTime(orderDetail.payCarTime)" />
          <nut-cell v-if="orderDetail.otherMessage" title="其他信息" :desc="orderDetail.otherMessage" />
        </nut-cell-group>

        <!-- 保险信息 -->
        <nut-cell-group v-if="hasInsuranceInfo" :title="'保险信息'">
          <nut-cell title="商业保险单号" :desc="orderDetail.insuranceNo || '--'" />
          <nut-cell title="商业保险公司" :desc="orderDetail.insuranceCompany || '--'" />
          <nut-cell title="商业保险开始时间" :desc="formatTime(orderDetail.insuranceStartTime)" />
          <nut-cell title="商业保险结束时间" :desc="formatTime(orderDetail.insuranceEndTime)" />
        </nut-cell-group>

        <!-- 支付信息列表 -->
        <nut-cell-group v-if="orderDetail.payInfoList && orderDetail.payInfoList.length > 0" title="支付记录">
          <nut-cell
            :title="`支付记录 (${orderDetail.payInfoList.length}条)`"
            is-link
            @click="togglePayList"
          >
            <template #desc>
              <component :is="payListExpanded ? ArrowUp : ArrowDown" />
            </template>
          </nut-cell>
          <div v-if="payListExpanded" class="pay-list-content">
            <div
              v-for="(payInfo, index) in orderDetail.payInfoList"
              :key="payInfo.payId || index"
              class="pay-info-card"
            >
              <div class="pay-info-header">
                <span class="pay-info-title">支付记录 {{ index + 1 }}</span>
                <nut-tag :type="getPayStatusTagType(payInfo.payStatus)">{{ payInfo.payStatusName || '--' }}</nut-tag>
              </div>
              <div class="pay-info-body">
                <div class="pay-info-row">
                  <span class="label">支付流水号:</span>
                  <span class="value">{{ payInfo.payNo || '--' }}</span>
                </div>
                <div class="pay-info-row">
                  <span class="label">支付类型:</span>
                  <span class="value">{{ payInfo.payTypeName || '--' }}</span>
                </div>
                <div class="pay-info-row">
                  <span class="label">已支付金额:</span>
                  <span class="value">{{ formatAmount(payInfo.paidAmount) }}</span>
                </div>
                <div class="pay-info-row">
                  <span class="label">支付时间:</span>
                  <span class="value">{{ formatTime(payInfo.paidTime) }}</span>
                </div>
              </div>
              <div class="pay-info-footer">
                <nut-button size="small" type="primary" plain @click.stop="goToPayDetail(payInfo.payId)">
                  查看详情
                </nut-button>
              </div>
            </div>
          </div>
        </nut-cell-group>

        <!-- 附件列表 -->
        <nut-cell-group v-if="orderDetail.fileList && orderDetail.fileList.length > 0" title="附件">
          <nut-cell v-for="(file, index) in orderDetail.fileList" :key="index" :title="`附件 ${index + 1}`">
            <template #desc>
              <a :href="file" target="_blank" class="file-link">查看附件</a>
            </template>
          </nut-cell>
        </nut-cell-group>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <nut-button v-if="canUpdate" type="primary" block @click="goToUpdate">修改订单</nut-button>
          <nut-button v-if="canSupplement" type="primary" block @click="goToSupplement">补录</nut-button>
          <nut-button v-if="canPay" type="primary" block @click="goToPay">
            {{ isPartialPay ? '继续支付' : '立即支付' }}
          </nut-button>
          <nut-button v-if="canCancel" type="danger" block @click="handleCancel">取消订单</nut-button>
        </div>
      </div>

      <div v-else class="empty-state">
        <nut-empty description="订单不存在" />
      </div>
    </nut-pull-refresh>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showDialog } from '@nutui/nutui';
  import { Clock, Check, Close, ArrowUp, ArrowDown } from '@nutui/icons-vue';
  import { fetchOrderDetail, cancelPay, type OrderDetail, type OrderPayInfo } from '@/api/order';
  import dayjs from 'dayjs';

  const router = useRouter();
  const route = useRoute();

  const orderDetail = ref<OrderDetail | null>(null);
  const loading = ref(false);
  const refreshing = ref(false);

  // 计算属性
  const hasVehicleInfo = computed(() => {
    return !!(
      orderDetail.value?.vinCode ||
      orderDetail.value?.engineNumber ||
      orderDetail.value?.licensePlateNumber ||
      orderDetail.value?.vehicleType ||
      orderDetail.value?.model
    );
  });

  const hasInsuranceInfo = computed(() => {
    return !!(orderDetail.value?.insuranceNo || orderDetail.value?.insuranceCompany);
  });

  // 支付列表展开状态
  const payListExpanded = ref(false);

  // 只有补录之后的订单才可以修改
  const canUpdate = computed(() => {
    return orderDetail.value?.supplementStatus === '01';
  });

  // 生成订单后可以补录（已支付且未补录）
  // 已补录过的订单不再显示补录按钮
  const canSupplement = computed(() => {
    if (!orderDetail.value) return false;
    // 如果已补录，不显示补录按钮
    if (orderDetail.value.supplementStatus === '01') {
      return false;
    }
    // 只有已支付且未补录的订单才显示补录按钮
    return orderDetail.value.orderStatus === '01';
  });

  // 待支付或部分支付（有未支付金额）可以支付
  const canPay = computed(() => {
    const unpaidAmount = orderDetail.value?.unpaidAmount || 0;
    return (
      (orderDetail.value?.orderStatus === '00' || unpaidAmount > 0) && unpaidAmount > 0
    );
  });

  // 判断是否为部分支付
  const isPartialPay = computed(() => {
    const unpaidAmount = orderDetail.value?.unpaidAmount || 0;
    const paidAmount = orderDetail.value?.paidAmount || 0;
    return unpaidAmount > 0 && paidAmount > 0;
  });

  const canCancel = computed(() => {
    return orderDetail.value?.orderStatus === '00';
  });

  // 加载订单详情
  const loadOrderDetail = async () => {
    const orderId = route.query.orderId as string;
    if (!orderId) {
      showToast.text('订单ID不能为空');
      router.back();
      return;
    }

    try {
      loading.value = true;
      const { code, data, msg }: any = await fetchOrderDetail(orderId);
      if (code !== 200) {
        showToast.text(msg || '获取订单详情失败');
        return;
      }
      const detail = data as OrderDetail;
      orderDetail.value = detail || null;
    } catch (error: any) {
      console.error('获取订单详情失败', error);
      showToast.text(error?.message || '获取订单详情失败');
    } finally {
      loading.value = false;
    }
  };

  // 格式化时间
  const formatTime = (time?: string) => {
    if (!time) return '--';
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
  };

  // 格式化金额
  const formatAmount = (amount?: number) => {
    if (amount === undefined || amount === null) return '--';
    return `¥${amount.toFixed(2)}`;
  };

  // 获取状态标签类型
  const getStatusTagType = (status?: string) => {
    switch (status) {
      case '00':
        return 'warning';
      case '01':
        return 'success';
      case '02':
        return 'danger';
      default:
        return 'default';
    }
  };

  // 获取审核状态标签类型
  const getReviewStatusTagType = (status?: string) => {
    switch (status) {
      case '00':
        return 'default';
      case '01':
        return 'warning';
      case '02':
        return 'success';
      case '03':
        return 'danger';
      default:
        return 'default';
    }
  };

  // 获取支付状态标签类型
  const getPayStatusTagType = (status?: string) => {
    switch (status) {
      case '00':
        return 'warning';
      case '01':
        return 'success';
      case '02':
        return 'danger';
      default:
        return 'default';
    }
  };

  // 获取订单状态图标组件
  const getStatusIcon = (status?: string) => {
    switch (status) {
      case '00':
        return Clock; // 待支付
      case '01':
        return Check; // 支付成功
      case '02':
        return Close; // 已取消
      default:
        return '';
    }
  };

  // 跳转到修改订单页
  const goToUpdate = () => {
    router.push({
      path: '/order/update',
      query: { orderId: orderDetail.value?.orderId },
    });
  };

  // 跳转到补录页
  const goToSupplement = () => {
    router.push({
      path: '/order/supplement',
      query: { orderId: orderDetail.value?.orderId },
    });
  };

  // 切换支付列表展开状态
  const togglePayList = () => {
    payListExpanded.value = !payListExpanded.value;
  };

  // 跳转到支付页
  const goToPay = () => {
    // 待支付：跳转到支付页面
    // 部分支付：跳转到输入金额页面（也是支付页面，但会显示输入金额）
    router.push({
      path: '/order/pay',
      query: { orderId: orderDetail.value?.orderId },
    });
  };

  // 跳转到支付详情页
  const goToPayDetail = (payId?: string) => {
    if (!payId) return;
    router.push({
      path: '/order/pay',
      query: { payId },
    });
  };

  // 取消订单
  const handleCancel = () => {
    showDialog({
      title: '提示',
      content: '确定要取消该订单吗？',
      onOk: async () => {
        if (!orderDetail.value?.payInfoList || orderDetail.value.payInfoList.length === 0) {
          showToast.text('没有可取消的支付记录');
          return;
        }

        // 取消第一个待支付的支付记录
        const pendingPay = orderDetail.value.payInfoList.find((pay) => pay.payStatus === '00');
        if (!pendingPay?.payId) {
          showToast.text('没有可取消的支付记录');
          return;
        }

        try {
          await cancelPay({ payId: pendingPay.payId });
          showToast.text('取消成功');
          loadOrderDetail();
        } catch (error: any) {
          console.error('取消订单失败', error);
          showToast.text(error?.message || '取消订单失败');
        }
      },
    });
  };

  // 初始化
  onMounted(() => {
    loadOrderDetail();
  });
</script>

<style lang="scss" scoped>
  .order-detail-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 20px;
  }

  .loading-state {
    padding: 100px 20px;
    text-align: center;

    .loading-text {
      font-size: 28px;
      color: #666;
    }
  }

  .detail-content {
    .order-status-header {
      background-color: #fff;
      padding: 30px 20px;
      text-align: center;
      margin-bottom: 10px;

      .status-icon-wrapper {
        margin-bottom: 12px;

        .status-icon {
          width: 60px;
          height: 60px;
          font-size: 60px;

          &.status-00 {
            color: #ff9500; // 待支付 - 橙色
          }

          &.status-01 {
            color: #07c160; // 支付成功 - 绿色
          }

          &.status-02 {
            color: #ff3b30; // 已取消 - 红色
          }

          &.status-default {
            color: #666; // 默认 - 灰色
          }
        }
      }

      .status-text {
        font-size: 32px;
        font-weight: 600;
        color: #333;
      }
    }

    .pay-list-content {
      padding: 0 16px 16px;

      .pay-info-card {
        background-color: #f8f8f8;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 12px;

        .pay-info-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          padding-bottom: 12px;
          border-bottom: 1px solid #e0e0e0;

          .pay-info-title {
            font-size: 28px;
            font-weight: 600;
            color: #333;
          }
        }

        .pay-info-body {
          .pay-info-row {
            display: flex;
            margin-bottom: 8px;
            font-size: 24px;

            .label {
              color: #666;
              margin-right: 10px;
              min-width: 140px;
            }

            .value {
              color: #333;
              flex: 1;
            }
          }
        }

        .pay-info-footer {
          margin-top: 12px;
          text-align: right;
        }
      }
    }

    .file-link {
      color: #1989fa;
      text-decoration: none;
    }

    .action-buttons {
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 15px;
      margin-top: 20px;
    }
  }

  .empty-state {
    padding: 100px 20px;
    text-align: center;
  }
</style>

